﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediatR;

namespace Extensions.Interceptor.Event;

public class EventHandler:INotificationHandler<EventModel>
{
    private readonly IEnumerable<IEventHandler> _eventHandlers;

    public EventHandler(IEnumerable<IEventHandler> eventHandlers)
    {
        _eventHandlers = eventHandlers?? throw new ArgumentNullException(nameof(eventHandlers));
    }
    public async Task Handle(EventModel notification, CancellationToken cancellationToken)
    {
        if (string.IsNullOrWhiteSpace(notification.EventName))
        {
            return;
        }

        var handle = _eventHandlers.FirstOrDefault(p => p.EventName == notification.EventName);
        if (handle != null)
        {
            await handle.Handle();
        }
    }
}